import DefaultImage from '@/asset/default-image.png';
import { listAllAddresses } from '@/service/query/address';
import { listNearbyShops } from '@/service/query/shop';
import Link from 'next/link';
import DownToTopView from '../common/motion/down-to-top-view';
import QueryImage from '../common/query-image';
import AddressSelector from './address-selector';
import Pagination from './pagination';
import TakeoutSearchBar from './takeout-search-bar';

export default async function NearbyShopList({
  searchParams,
}: { searchParams: Record<string, any> }) {
  const { result: addresses, error } = await listAllAddresses();
  if (error) return <div className="text-center py-10">{error.message}</div>;

  const selectedAddress = searchParams.addressId
    ? addresses.find((address) => address.id === searchParams.addressId)
    : addresses[0];

  if (!selectedAddress)
    return <div className="text-center py-10">地址不存在</div>;

  const { result } = await listNearbyShops({
    page: searchParams.page,
    pageSize: searchParams.pageSize,
    longitude: selectedAddress.longitude,
    latitude: selectedAddress.latitude,
    range: searchParams.deliverRange,
    keywords: searchParams.keywords,
  });

  return (
    <div className="space-y-8">
      <div className="font-bold text-lg text-end">附近热销</div>
      <TakeoutSearchBar
        serverComps={{
          addressSelector: (
            <AddressSelector
              searchParams={searchParams}
              addresses={addresses}
              selectedAddress={selectedAddress}
            />
          ),
        }}
      />
      <DownToTopView>
        <div className=" space-y-8">
          {result?.data.map((shop) => (
            <Link
              key={shop.id}
              className="block"
              href={`/detail-shop/${shop.id}`}
            >
              <div className="flex gap-3 hover:bg-muted transition-colors rounded-lg cursor-pointer">
                <div className="shrink-0">
                  <QueryImage
                    imageKey={shop.imageKeys[0]}
                    defaultImage={DefaultImage}
                    wrapperClassName="w-40 h-28 rounded-lg"
                    imgClassName="object-cover w-full h-full rounded-lg"
                  />
                </div>
                <div className="py-2 px-1 relative">
                  <div className="font-bold text-lg">{shop.name}</div>
                  <div className="text-sm text-muted-foreground">
                    {shop.description}
                  </div>
                  <div className="text-xs text-muted-foreground absolute bottom-1">
                    订单量: {shop.orderCount}
                  </div>
                </div>
              </div>
            </Link>
          ))}
        </div>
      </DownToTopView>
      <Pagination next={result?.next ?? null} />
    </div>
  );
}
